#Skytank project
#Author: Leo Szeto
#Last updated: 2/8/2011
#Abstract: Skype controlled telepresense robot. Can be ordered to move across terrain wherever wifi is available.

#Dedicated to Michelle, for being my inspiration for this project.

#Import python libraries
import sys, math, time, string, os

#Import wrapper libraries
import Skype4Py #Netbook -> Internet layer
import serial   #Netbook -> Circuits layer

#Import custom libraries
import Skytank_utils
from Skytank_utils import *
#Keeps track of the system's state
sys_state = 0

#----------------------------------------------------
#INITIALIZATION - SKYPE
#----------------------------------------------------
#Attach functions to these events. 
skype.OnAttachmentStatus = OnAttach
skype.OnMessageStatus = OnMessageStatus
skype.OnCallStatus = OnCall

#connect to the Skype class, if this is the script's
#first run, it will most likely ask for permission.
skype.Attach()
print "Skype wrapper is now attached."

#Should be part of the Skype init function, or run once every 5 minutes or so.
#Grab a list of all authorized personnel (friends)
print "Grabbing list of users"
auth_users =[]
for user in skype.Friends:
	auth_users.append(user.Handle)
	print "     " + user.Handle

#----------------------------------------------------
#INITIALIZATION - Serial
#----------------------------------------------------
#Create an instance of the serial class and link it
#to the arduino
tries = 0
while tries < 5: #Will try up to 5 ports
	try:
		#ser.close()
		ser = serial.Serial('/dev/ttyUSB0', 9600, timeout = 0.5)
		tries = 5
	except serial.serialutil.SerialException:
		print "Failed to open Serial port!"
		tries = tries + 1
		#TO ADD: Must if it fails for the last time, exit.

print "Starting Serial interface - wait 2 seconds"
time.sleep(2) #2 second delay to allow for arduino to be ready.
#Do some handshaking to ensure that a connection
#has been made. We should write to the device first.
print "Starting handshake"
cmd = Skytank_utils.handshake(ser, 5, .25)
#Split the cmd into instr and parameters
print cmd
instr = cmd[:4]
param = cmd[4:]

if instr == "ARDY":
	print "Commad: " + instr
	print "Parmeters: " + param
	sys_state = 1 				#We have successfully linked with the arduino
if instr == "FAIL":				#Use the param to figure out the failure mode
	if param == "CODE":
		print "ERROR: Invalid cmd"
	if param == "LINK":
		print "ERROR: Cannot find arduino"
	sys_state = -1;

#Now the system will continuously listen for commands received 
#from skype and from the arduino.
print "Listening..."
while sys_state == 1:
	#Skype4Py uses an event handler to automatically listen to any chat messages
	#received. We use this as our entry point to parse -> execute commands
	
	#This leaves us with handling our own serial listening protocol.
	#we do this in a similar way to the handshake: Wait for enough characters
	#on the buffer and then parse -> execute. 
	cmd = Skytank_utils.serial_listen(ser)
	if cmd != "": 	
		print "Serial command received: " + cmd			#Check if we have a command in the pipe
		instr = cmd[:4]						#Parse out the instruction
		param = cmd[4:]						#Parse out the parameters
if sys_state == -1:
	print "Goodbye!"
